<template>
  <u-upload
    class="upload-image"
    uploadIcon="plus"
    :disabled="disabled"
    :maxCount="limit"
    :width="width"
    :height="height"
    :fileList="images"
	:deletable="!disabled"
    @afterRead="afterRead"
    @delete="deletePic"
  ></u-upload>
</template>

<script>
import upload from '@/utils/upload';
export default {
  name: 'upload-image',
  options: {
    styleIsolation: 'shared' // 解除样式隔离
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Array],
      default: ''
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 图片数量
    limit: {
      type: Number,
      default: 1
    },
    width: {
      type: [Number, String],
      default: '66px'
    },
    height: {
      type: [Number, String],
      default: '66px'
    }
  },
  data() {
    return {
      baseUrl: getApp().globalData.config.baseUrl,
      images: [],
      uploadList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : val.split(',');
          this.uploadList = list;
          // 然后将数组转为对象数组
          this.images = list.map(item => {
            if (typeof item === 'string') {
              if (item.indexOf(this.baseUrl) === -1) {
                item = {
                  name: this.baseUrl + item,
                  url: this.baseUrl + item,
                  status: 'success'
                };
              } else {
                item = {
                  name: item,
                  url: item,
                  status: 'success'
                };
              }
            }
            return item;
          });
          // console.log(this.images);
        } else {
          this.images = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    },
    uploadList: {
      handler(val) {
        // const urls = val.filter(item => item.status === 'success').map(item => item.url);
        // console.log(urls);
        // console.log('watch', val);
        this.$emit('input', val.toString());
      }
    }
  },
  methods: {
    // 删除图片
    deletePic(event) {
      if (this.images.length === this.uploadList.length) this.uploadList.splice(event.index, 1);
      this.images.splice(event.index, 1);
    },
    // 选择图片
    async afterRead(event) {
      const { file } = event;
      if (!this.uploadFileValidate(file)) return false;
      this.$modal.loading('正在上传图片');
      this.images.push({
        ...file,
        status: 'uploading',
        message: '上传中'
      });
      this.uploadFilePromise(file.url);
    },
    // 校验文件
    uploadFileValidate(file) {
      // console.log(file);
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = '';
        let fileUrl = file.name ? file.name : file.url;
        if (fileUrl.lastIndexOf('.') > -1) {
          fileExtension = fileUrl.slice(fileUrl.lastIndexOf('.') + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf('image') > -1;
      }
      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          // this.$modal.msgError(`上传的图片大小不能超过 ${this.fileSize} MB!`);
          this.$modal.msgError(`上传的图片过大！`);
          return false;
        }
      }
      return true;
    },
    // 上传图片
    uploadFilePromise(url) {
      let fileListLen = this.images.length;
      upload({
        url: '/common/v2/upload',
        filePath: url
      })
        .then(res => {
          this.$modal.closeLoading();
          this.uploadFileSuccess(res.fileName, fileListLen);
        })
        .catch(err => {
          this.$modal.closeLoading();
          this.$modal.msgError('上传失败');
          this.deletePic({ index: fileListLen });
        });
    },
    // 上传成功
    uploadFileSuccess(url, idx) {
      this.$set(this.images, idx, {
        status: 'success',
        message: '成功',
        url
      });
      this.uploadList.push(url);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .u-upload {
  .u-upload__wrap {
    padding: -8px;

    .u-upload__wrap__preview,
    .u-upload__button {
      // margin: 8px 8px 8px 0;
    }
	
    .u-upload__deletable {
      height: 20px;
      width: 20px;

      .u-upload__deletable__icon {
        transform: scale(0.9);
        top: 10%;
        right: 10%;
      }
    }
  }
}
::v-deep .u-upload__button{
		margin: 0 !important;
	}
</style>
